<?php

namespace Utuo;

use Utuo\WechatAdvance;
use Think\Controller;
use My\Model\WechatUserModel;
use My\Model\UserRole;

class DistributionShopForeground extends Controller {
	
	/**
	 * 每页显示条数
	 *
	 * @var int
	 */
	protected $pageSize = 10;
	
	/**
	 * 登录时间SESSION键名
	 * @var unknown
	 */
	const LOGIN_TIME = '_login_time_';
	
	/**
	 * 登录用户sessionKey
	 * @var unknown
	 */
	const USER_SESSION_KEY = "wechat_user";
	
	/**
	 * 登录超时时间
	 * @var unknown
	 */
	const LOGIN_EXPIRES = 120; // 2分钟
	
	/**
	 * 跳转状态码
	 * @var unknown
	 */
	const STATE_CODE = 'utuo';
	
	/**
	 * 登录用户sessionKey
	 */
	protected $sessionKey;
	
	/**
	 * 高级接口
	 * @var unknown
	 */
	protected $wechatAdvance;
	
	/**
	 * 微信id
	 * @var unknown
	 */
	protected $openId = 0;
	
	/**
	 *  客户id
	 * @var unknown
	 */
	protected $cid = 0;
	
	/**
	 * 用户id
	 * @var unknown
	 */
	protected $uid = 0;
	
	/**
	 * 用户代理商id
	 * @var unknown
	 */
	protected $aid = 0;
	
	/**
	 * 是否检查登录
	 * @var unknown
	 */
	protected $checkLogin = true;
	
	/**
	 * 是否支持跳转
	 * @var unknown
	 */
	protected $supportRedirect = false;
	
	/**
	 * 跳转额外参数
	 * @var unknown
	 */
	protected $redirectParams = array();
	
	/**
	 * 网站信息
	 * @var array
	 */
	protected $config = array ();
	
	/**
	 * 微信设置
	 * @var array
	 */
	protected $wechatConfig = array();
	
	/**
	 * 网站主题信息
	 * @var array
	 */
	protected $theme = array ();
	
	/**
	 * 模型名称
	 * @var unknown
	 */
	protected $modelName = "";
	
	/**
	 * 模型控制器名称
	 * @var unknown
	 */
	protected $modelControllerName = "";
	
	/**
	 * 分享数据
	 * @var unknown
	 */
	protected $share = array();
	
	/**
	 * 页面标题
	 * @var string
	 */
	private $pageTitle = '';
	
	/**
	 * 获得当前页码
	 *
	 * @return int
	 */
	protected function getPage() {
		return I('p', 1, 'intval');
	}
	
	/**
	 * 获取分页大小
	 *
	 * @return number
	 */
	protected function getPageSize() {
		$this->pageSize = I('pageSize', 10, 'intval');
		return $this->pageSize;
	}
	
	
	/**
	 * 设置是否支持分享
	 * @param unknown $shareEnabled
	 */
	protected function setShareEnabled($shareEnabled) {
		$this->shareEnabled = $shareEnabled;
	}
	
	/**
	 * 设置是否支持跳转
	 * @param unknown $supportRedirect
	 */
	protected function setSupportRedirect($supportRedirect) {
		$this->supportRedirect = $supportRedirect;
	}
	
	/**
	 * 设置跳转的额外参数
	 * @param unknown $params
	 */
	protected function setRedirectParams($params){
	    is_array($params) && ($this->redirectParams = array_merge($this->redirectParams,$params));
	}
	
	/**
	 * 设置是否检查登录
	 * @param unknown $checkLogin
	 */
	protected function setCheckLogin($checkLogin) {
		$this->checkLogin = $checkLogin;
	}
	
	/**
	 * 设置模型
	 * 
	 * @param string $name
	 */
	protected function setModelName($name = null) {
		$name or $name = CONTROLLER_NAME;
		$this->modelName = $name;
	}
	
	/**
	 * 设置模型控制器名
	 * 
	 * @param string $name
	 */
	protected function setModelControllerName($name = null) {
		$name or $name = CONTROLLER_NAME;
		$this->modelControllerName = $name;
	}
	
	/**
	 * 设置页面标题
	 *
	 * @param string $pageTitle
	 */
	public function setPageTitle($pageTitle, $suffix = null) {
		$this->pageTitle = $pageTitle;
		empty($suffix) or $this->pageTitle .= ' - ' . $suffix;
		return $this;
	}
	
	/**
	 * 设置分享内容
	 * @param unknown $config
	 * array(
	 * 	  'imgUrl' => '',
	 * 	  'link' => '',
	 *    'desc' => '',
	 *    'title' => '',
	 * )
	 */
	public function setShare( $config ) {
		$this->share = array_merge( $this->share, $config );
	} 
	
	protected function appExit($msg){
	    header("Content-Type: text/html; charset=UTF-8");
	    die($msg);
	}
	
	/**
	 * 重构display
	 * 
	 * @see \Think\Controller::display()
	 */
	protected function display($templateFile = '', $charset = '', $contentType = '', $content = '', $prefix = '') {
		C('TMPL_PARSE_STRING.__DEFAULT__', __ROOT__ . '/Public/Style/' . MODULE_NAME . '/Default');
		C('TMPL_PARSE_STRING.__COMMON__', __ROOT__ . '/Public/Style/Common');
		// layout(false);
		C('TMPL_PARSE_STRING.__TITLE__', $this->pageTitle ?  : $this->config['name']); 
		
		/* 分享 */
		$this->share['title'] or $this->share['title'] = C('TMPL_PARSE_STRING.__TITLE__');
		$this->share['imgUrl'] or $this->share['imgUrl'] = $this->user['face'] ? $this->user['face'] : $this->config['logo'] ? $this->config['logo'] : '';
		$this->share['link'] or $this->share['link'] = 'http'.(isset($_SERVER['HTTPS']) ? 's' : '').'://'.$_SERVER['HTTP_HOST'].(($_SERVER['SERVER_PORT'] == 80 || $_SERVER['SERVER_PORT'] == 443) ? '' : ':'.$_SERVER['SERVER_PORT']).$_SERVER['REQUEST_URI'];
		$this->share['desc'] or $this->share['desc'] = $this->config['description'];
		$this->share = array_filter($this->share);
		$this->assign("share", empty($this->share) ? "{}" : json_encode($this->share) );
		
		/* WECHAT JSAPI 签名包 */
		if ( empty($this->error) ) {
			if ( $this->wechatAdvance ) {
				$signPackage = $this->wechatAdvance->getSignPackage();
				$this->assign("wxConfig", $signPackage);
			} else {
				echo "签名包未生成";
			}
		}
		parent::display($templateFile,$charset,$contentType,$content,$prefix);
	}
	
	/**
	 * 构造函数
	 */
	public function __construct() {
		parent::__construct();
		$this->tid = I("get.tid", 0, "intval") or $this->tid = I("post.tid", 0, "intval");
		$this->cid = I('get.sid', 0, 'intval') or $this->cid = I("post.sid", 0, "intval");
		$this->sid = $this->cid;
		if (!$this->cid) {
			$this->cid = C('DEFAULT_SITE_ID');
		}
		$this->assign("sid", $this->sid);
		$this->sessionKey = self::USER_SESSION_KEY.'_'.$this->cid;
		session("sessionKey", $this->sessionKey);
		$this->openIdKey = "openId{$this->cid}";
		session("openIdKey", $this->openIdKey);
		
		if ( isset( $_REQUEST['debug'] ) and $_REQUEST['debug'] == 'zhangrui.songyi') {
			$user = session($this->sessionKey);
			$debugUid = $_REQUEST['debugUid'] or $debugUid = 0;
			if (!$user or !$user['id'] or ($debugUid and $user and $user['id'] != $debugUid) ) {
				$condition = array( 'cid' => $this->cid, );
				$debugUid and $condition['id'] = $debugUid;
				$vuser = M("WechatUser")->where($condition)->find();
				$this->setOpenId($vuser['openId']);
				$this->setLogin($vuser);
			}
		}
		
		$this->setOpenId();
		$this->getLogin();
		
		method_exists($this, '_init') && $this->_init();
		
		/* 模型配置 */
		$modelName = $this->modelName;
		if ( $modelName ) {
		    $config = $this->getModelConfig();
		    if ($config['status'] != 1) $this->responseMsg("网站已关闭");
		    $this->tid === 0 and $this->tid = $config['theme'];
		    $themeConfig = $this->getThemeConfig($this->tid, $config);
		    $this->assign('style', $themeConfig);
		    $config['url'] = url('Home', $this->modelControllerName ? $this->modelControllerName : $modelName, '', array (
		        'sid' => $this->sid
		    ));
		    $this->config = $config;
		    $this->assign("config", $config);
		    $this->assign(lcfirst($modelName), $config);
		}
		
		//echo 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING'];
		//ini_set("display_errors",false);
		//sae_debug('---http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']);
		
		/* 推广处理 */
		// 微信设置
		$this->wechatConfig = $wechat = M("Wechat")->cache(true)->where('cid=%d', $this->cid)->find();
		if ( empty($wechat['appid']) or empty($wechat['appsecret']) ) {
		    $this->responseMsg('请设置微信开发者配置信息');
		}
		$this->wechatAdvance = new WechatAdvance($wechat['appid'], $wechat['appsecret']);
		
		// 支持跳转获得用户信息并登录
		if ( $this->supportRedirect ) {
			$this->promotionEnter();
		}

		// 跳转后执行
		method_exists($this, '_after_redirect') && $this->_after_redirect();
		
		// 检查登录
		if ( $this->requireLogin() ) {
		    if ( !$this->uid ) {
		        if (IS_AJAX) {
		            $this->ajaxError("还未登录,请重新打开首页系统将自动完成登录.");
		        } else {
		            /* 刷新用户信息 */
		            $user = $this->refreshWechatUser();
		            $this->setLogin($user);
		            if (!$this->uid) {
		                $this->responseMsg('您的微信账号未能成功登录系统');
		            }
		        }
		    }
		    // 设置当前代理
		    $this->aid = $this->getRequestAid();
		    $this->setAid( $this->aid );
		}
		
		// 分享人信息
		$fromUser = M("WechatUser")->cache(true)->where(array (
				'cid' => $this->cid,
				'id' => $this->user['mid'],
		))->find();
		$this->assign('fromUser', $fromUser);
		
		// 登录用户
		$assignUser = $this->user;
		$assignUser and $assignUser['subscribe'] = ($assignUser['subscribe']*1 ? 1 : 0);
		$assignUser and $assignUser["typeName"] = WechatUserModel::getUserTypeName($assignUser['type'], $assignUser['id']);
		$this->assign('user', $assignUser);
		$this->assign("openId", $this->openId);
		
		/* 主题设置 */
		$themeStyle = 'Default';
		$themeTemplate = 'Default';
		if (!empty($this->tid)) {
			$theme = M("Theme")->cache(true)->find($this->tid);
			$themeStyle = $theme['style'];
			$themeTemplate = $theme['template'];
		}
		
		// ################### 开始 处理客户前台技术支持 #####################
		// 系统的技术支持
		$system = M('system')->cache(true)->find();
		
		// 客户及合作商技术支持
		$customer = M("Customer c")->where(array('c.id'=>$this->cid))->join("LEFT JOIN __PARTNER__ p ON c.partner=p.id")->field("c.partner,c.support,c.support_type,p.support AS partner_support,p.support_allowed AS partner_support_allowed")->find();
		
		// 客户前台技术支持显示类型(0=自动,9=不显示,1=系统,2=合作商,3=客户)
		switch ($customer['support_type']){
		    case 0:
		        $support = $customer['partner_support_allowed'] ? $customer['partner_support'] : $system['support'];
		        break;
		    case 1: 
		        $support = $system['support'];
		        break;
		    case 2:
		        $support = $customer['partner_support'];
		        break;
		    case 3:
		        $support = $customer['support'];
		        break;
		    case 9:
		        $support = '';
		        break;
		    default:
		        $support = $system['support'];
		}
		
		// 显示客服QQ
		if (!empty($this->config['qq'])){
		    $qqWidget = sprintf('<div style="position: fixed; bottom: 58px; right: 10px;"><a target="_blank" href="http://wpa.qq.com/msgrd?v=3&uin=%s&site=qq&menu=yes"><img border="0" src="http://wpa.qq.com/pa?p=2:%s:51" alt="点击这里给我发消息" title="点击这里给我发消息"/></a></div>',$this->config['qq'],$this->config['qq']);
		    $support .= "\n\n".$qqWidget;
		}
		
		$system['bottom'] = $support;
		$this->assign('system', $system);
// 		$this->assign('customer',$customer);
		// ################### 结束 处理客户前台技术支持 #####################
		
		C('TMPL_PARSE_STRING.__STYLE__', __ROOT__ . '/Public/Style/' . MODULE_NAME . '/' . $themeStyle);
		
		parent::theme($themeTemplate);
		
		C('TMPL_ACTION_ERROR', './error'); // 默认错误跳转对应的模板文件
		C('TMPL_ACTION_SUCCESS', './success'); // 默认成功跳转对应的模板文件
		
		// 记录客户PV
		PVReport::report($this->cid); 
// 		\Utuo\UtuoLog::doLogPost("WmflFront", array(
// 			'user' => session($this->sessionKey),
// 		));
	}
	
	/**
	 * 登录相关SESSION名
	 * 
	 * @var array
	 */
	private $sessionKeys = array ();
	
	/**
	 * 当前session中的用户信息
	 * 
	 * @var unknown
	 */
	protected $user = null;
	
	/**
	 * 获得主题配置
	 * 
	 * @param $tid 选择的主题
	 * @return $config 当前的主题设置
	 */
	private function getThemeConfig($tid, $config) {
		$themeConfig = M("ThemeConfig")->cache(true)->where("cid=%d and theme=%d", $this->cid, $tid)->getField("config");
		$themeConfig = unserialize($themeConfig);
		return $themeConfig;
	}
	
	
	/**
	 * 获得渠道id
	 * @return Ambigous <mixed, void, NULL, multitype:, unknown, string>
	 */
	protected function getQid() {
		$qid = $this->qid or $qid = I('request.qid', 0, "intval") or $qid = cookie('_qid_'.$this->cid)*1;
		return $qid;
	}
	
	/**
	 * 设置渠道id
	 * @param unknown $aid
	 */
	protected function setQid( $qid ) {
		$this->qid = $qid*1;
		cookie('_qid_'.$this->cid, $qid ? $qid : null);
	}
	
	/**
	 * 获得当前代理信息
	 * @return unknown
	 */
	protected function getCurrentAgent() {
	    $currentAgent = M("Agent a")->join("__WECHAT_USER__ b on a.wechat_uid=b.id")->where(array('a.cid'=>$this->cid, 'a.id'=>$this->aid))->field("a.*,b.nickname")->find();
	    return $currentAgent;
	}
	
	/**
	 * 获得最新代理商id(用于推广)
	 * @return Ambigous <mixed, void, NULL, multitype:, unknown, string>
	 */
	protected function getRequestAid() {
	    DBRW::openAndClose(0);
		$aid = I('aid', 0, "intval");
        if ( !$aid ) { // 未传代理id
            $userRole = new UserRole();
            if ( $userRole->type($this->user['type'])->is(WechatUserModel::USER_TYPE_AGENT) ) {
                // 当前推广代理商为本人
                $aid = M("Agent")->where(array('wechat_uid' => $this->user['id']))->getField("id");
            }  else {
                $aid = M("WechatUser")->where(array("cid"=>$this->cid, "id" => $this->uid))->getField("tmpAid");
                if ( empty($aid) ) {
                    /* 从代理推荐人处购买 */
                    $pUid = $this->user['id'];
                    do {
                        $wechatUser = M("WechatUser")->where(array('cid'=>$this->cid, 'id'=>$pUid))->find();
                        if ( $userRole->type($wechatUser['type'])->is(WechatUserModel::USER_TYPE_AGENT) ) {
                            $agent = M("Agent")->where("cid=%d and wechat_uid=%d", $this->cid, $wechatUser['id'])->find();
                            if ( $agent ) {
                                $aid = $agent['id'];
                                break;
                            }
                        }
                        $pUid = $wechatUser['mid'];
                    } while( $pUid );
                }
            }
        }
        if ( !($this->checkAid($aid)) ) { // 代理商已删除
            $aid = 0;
        }
		DBRW::openAndClose(1);
		return $aid;
	}
	
	/**
	 * 设置代理商id
	 * @param unknown $aid
	 */
	protected function setAid( $aid ) {
	    // 设置临时代理商
	    M("WechatUser")->where(array("cid"=>$this->cid, "id" => $this->uid))->setField("tmpAid", $aid );
	}
	
	/**
	 * 获得购买时的代理商家ID
	 * @param unknown $deliverAddress
	 * @return Ambigous <number, \Utuo\unknown, unknown>
	 */
	protected function getRealAid( $deliverAddress ) {
	    $aid = $this->aid; // 当前供货代理商id
	    $userRole = new UserRole();
	    if ( $userRole->type($this->user['type'])->is(WechatUserModel::USER_TYPE_AGENT) ) { // 购买者是代理商
	        /* 厂家 */
	        $aid = 0;
	    } else {
	        if ( !$aid ) { // 无代理
	            $provinceCode = $deliverAddress['province'];
	            $cityCode = $deliverAddress['city'];
	            $areaCode = $deliverAddress['area'];
	            if ( !!($areaAgentList = M("Agent")->where("cid=%d and area='%s' and is_loc_type=3", $this->cid, $areaCode)->select()) ) { // 区代
	                $aid = $areaAgentList[0]['id'];
	            } elseif ( !!($cityAgentList = M("Agent")->where("cid=%d and city='%s' and is_loc_type=2", $this->cid, $cityCode)->select()) ) { // 市代
	                $aid = $cityAgentList[0]['id'];
	            } elseif ( !!($provinceAgentList = M("Agent")->where("cid=%d and province='%s' and is_loc_type=1", $this->cid, $provinceCode)->select()) ) { // 省代
	                $aid = $provinceAgentList[0]['id'];
	            }
	        }
	    }
	    return $aid;
	}
	
	
	/**
	 * 推广进入(当需要跳转时调用此方法)
	 * @return
	 */
	public function promotionEnter() {
		$state = I('state', 0);
		$mid = I('mid', 0, 'intval');
		$aid = $reqAid = $_REQUEST['aid']*1; // 请求参数中的aid
		$openId = 0;
		if ( !$this->requireLogin() or $this->checkLogin() ) {
		    $redirectParam = array();
			// 更改为可分享的地址
			if ( $this->uid ) {
			    // 推广人id
			    if ( $mid != $this->uid ) {
			        $redirectParam = array_merge($redirectParam, array (
			            'mid' => $this->uid, // 所有链接必须携带mid
			        ));
			    }
				// 推广代理
			    $reqAid or $aid = $this->getRequestAid();
			    if ( $reqAid != $aid ) {
			        $redirectParam = array_merge($redirectParam, array (
			            'aid' => $aid, // 所有链接必须携带aid
			        ));
			    }
			}
			if ( !empty( $redirectParam ) ) {
			    $url = $this->getRedirectUrl( $redirectParam ) ;
			    redirect( $url );
			}
		} elseif ($state === self::STATE_CODE) { // 第一次推广进入
			$code = I("code", 0);
			$authAccessRes = $this->wechatAdvance->getAuthAccessToken($code);
			if ( $authAccessRes != false ) {
				$openId = $authAccessRes['openid'];
				if ( $openId ) {
					$this->setOpenId( $openId );
					// 初始微信用户信息绑定
					$user = $this->bindUser(array(
						'mid' => $mid,
						'cid' => $this->cid,
						'openId' => $openId,
					));
					$this->setLogin($user);
					// 刷新用户信息(针对关注后)
					/*$user = $this->refreshWechatUser($openId, $user);
					if ($user and $user['isFresh']) {
						$this->setLogin($user);
					}*/
					// 更改为可分享的地址
					if ( isset($_GET['state']) or isset($_GET['code'])) {
						$redirectParam = array (
							'mid' => $this->uid,
						);
						$aid and $redirectParam['aid'] = $aid;
						$redirectUrl = $this->getRedirectUrl( $redirectParam );
						redirect($redirectUrl);
					} 
				}
			} else {
				$this->responseMsg("error:".$this->wechatAdvance->getError());
			}
		} else {
			$redirectUrl = $this->wechatAdvance->getAuthRedirectUrl($this->getRedirectUrl(), 0, self::STATE_CODE);
			redirect($redirectUrl);
		}
	}
	
	/**
	 * 增加与更新微信用户信息
	 * 
	 * @param unknown $openId
	 */
	private function refreshWechatUser($openId = 0, $user) {
		$openId or $openId = $this->openId;
		if( !$openId ) {
			return false;
		}
		$globalTokenRes = $this->wechatAdvance->getBaseAccess();
		if (false != $globalTokenRes) {
			$accessToken = $globalTokenRes['access_token'];
			$info = $this->wechatAdvance->getUserInfo($accessToken, $openId);
			if (false !== $info) {
				$userInfo = $this->bindUser(array (
						'cid' => $this->cid,
						'openId' => $openId,
						'isNew' => $user['isNew'],  // 是否新插入用户为true时可对用户信息直接更新
					), $info);
			    if ( isset($userInfo['errcode']) ) {
			        SystemInfo::log("WEB_NOT_USER_INFO", $userInfo);
			    }
				return $userInfo;
			}
		}
		return $this->bindUser(array (
				'cid' => $this->cid,
				'openId' => $openId 
		)); // 未更新获得当前已绑定的信息
	}
	
	/**
	 * 检测是否需要登录
	 * @return boolean
	 */
	protected function requireLogin() {
		$user = session($this->sessionKey);
		if ( $user['debug'] ) { // 调试模式下session无有效期
			return false;
		}
		return $this->checkLogin;
	}
	
	/**
	 * 检查登录
	 */
	protected function checkLogin() {
		$isLogined = true;
		$loginTime = session(self::LOGIN_TIME);
		$user = session($this->sessionKey);
		if ( $user and !$user['subscribe'] and (NOW_TIME - $loginTime * 1) > 10 ) { // 未关注十秒一检查关注
			$isLogined = false;
			$this->setLogout();
		} elseif (!$this->uid or !$loginTime or ($this->uid and (NOW_TIME - $loginTime * 1) > self::LOGIN_EXPIRES)) { // 检查登录超时
			$isLogined = false;
			$this->setLogout();
		}
		return $isLogined;
	}
	
	/**
	 * 获得session用户信息
	 * 
	 * @see \Utuo\ForegroundController::getLogin()
	 */
	protected function getLogin() {
		$user = session($this->sessionKey);
		$this->uid = $user['id'];
		$this->user = $user;
		return $user;
	}
	
	/**
	 * 设置登录
	 * 
	 * @param array $user array(
	 *        'id' => 1,
	 *        'mid' => 3,
	 *        'nickname'=> '',
	 *        'face'=> '',
	 *        )
	 */
	protected function setLogin($user) {
		/* 保存用户session */
		session($this->sessionKey, array (
				'id' => $user['id'],
				'openId' => $user['openId'],
				'mid' => $user['mid'],
				'nickname' => $user['nickname'],
				'face' => $user['face'],
				'subscribe' => $user['subscribe'],
				'debug' => $user['debug'],
				'type' => $user['type'],
		));
		$this->sessionKeys = array (
				'id',
				self::LOGIN_TIME 
		);
		session('id', $user['id']);
		session(self::LOGIN_TIME, NOW_TIME);
		session("sessionKeys", serialize($this->sessionKeys));
		/* 保存用户在系统的登录信息 */
		$adminData = array (
				'lastLoginTime' => NOW_TIME,
				'lastLoginIp' => get_client_ip(),
				'loginCount' => $user['loginCount'] + 1 
		);
		M('WechatUser')->where("id=" . $user['id'])->save($adminData);
		$this->getLogin();
	}
	
	/**
	 * 添加与更新微信用户
	 * 
	 * @param unknown $cid 客户id
	 * @param unknown $param 用户信息
	 * array(
	 *  'mid' => 0,
	 *  'openId' => 'oIoTWjua2ih8sgLaW-YJzRWy_2IM',
	 * )
	 * @param array $info 用户扩展信息(参考微信返回用户信息接口)
	 * array(
	 * 	'nickname' => '简单快乐',
	 *  'headimgurl' => '',
	 * )
	 * @return array(id,mid,cid,openId,face,nickname,subscribe[,loginCount])
	 */
	private function bindUser($param, $info) {
	    $openId = $param['openId'];
	    DBRW::openAndClose(0);
		$wechatUser = M("WechatUser")->where(array (
							'cid' => $this->cid,
							'openId' => $openId, 
					))->find();
		DBRW::openAndClose(1);
		if ( !$wechatUser and !$param['isNew'] ) { // 添加(刚插入数据可能无法查到用$param['isNew']再次判断)
			/*获得师傅信息*/
			$mid = $param['mid'] ? $param['mid'] : 0; // 师傅id
			DBRW::openAndClose(0);
			$mid and $masterWechatUser = M("WechatUser a")->join("__DISTRIBUTION_SHOP_USER_TREE__ b on a.id=b.uid", "LEFT")->where("a.cid=%d and a.id=%d", $this->cid, $mid)->field("a.*,b.tree,SUBSTRING_INDEX(b.tree,',',-1) as topId")->find(); // 师傅信息
			DBRW::openAndClose(1);
			if ( !$masterWechatUser ) {
				$mid = 0;
			} else {
				$tree = $masterWechatUser['tree'];
				$topId = $masterWechatUser['topId'];
				if ( empty($tree) ) { // 修复师傅的tree
				    /* 师傅tree */
				    $tree = $masterWechatUser['id'];
				    $tmpMid = $masterWechatUser['mid'];
				    $tree = $tmpMid.','.$tree;
				    while( $tmpMid*1 ) {
				        $tmpWechatUser = M("WechatUser")->where("id=%d", $tmpMid)->find();
				        $tree = $tmpWechatUser['mid'].','.$tree;
				        $tmpMid = $tmpWechatUser['mid'];
				    }
				    if ( false == M("DistributionShopUserTree")->add( array(
    				    'uid' => $masterWechatUser['id'],
    				    'cid' => $this->cid,
    				    'tree' => $tree,
    				    'length' => count(explode(',', $tree)),
				    )) ) {
				        return false;
				    }
				    /* 顶级id */
				    $topId = isset($tmpWechatUser['id']) ? $tmpWechatUser['id'] : 0;
				}
			}
			/*添加用户基础数据*/
			$addWechatUser = array (
					'mid' => $mid,
					'cid' => $this->cid,
					'qid' => $this->qid,
					'openId' => $param['openId'],
					'createTime' => time(),
					'type' => 1,
			);
			/*添加用户扩展数据*/
			if ( $info ) {
				$addWechatUser['face'] = $info['headimgurl'] ? $info['headimgurl'] : '';
				$addWechatUser['nickname'] = $info['nickname'] ? $info['nickname'] : '';
				$addWechatUser['subscribe'] = $info['subscribe'] ? $info['subscribe'] : 0;
			}
			$newId = M("WechatUser")->add($addWechatUser);
			
			if ( $newId ) {
				/* 添加用户后的后续处理 */
				$addWechatUser['id'] = $newId;
				if ( $mid ) { // 有师
				    $tree = $newId . ',' . $tree;
				} else { // 无师
				    $tree = $newId;
				}
				// 保存师徒关系
				M("DistributionShopUserTree")->add(array (
    				'uid' => $newId,
    				'cid' => $this->cid,
    				'tree' => $tree,
    				'length' => count(explode(',', $tree)),
				));
				
				/* 发送消息 */
				if ( $mid ) { // 有师
					$topWechatUser = M("WechatUser")->where(array ('id' => $topId,))->field('subCount,openId')->find();
				    // 师傅的徒弟数加一
					M("WechatUser")->where('id=%d', $mid)->setInc('sonCount', 1);
					// 徒弟的师傅字符串
					M('WechatUser')->where(array ('id' => array ('in', $masterWechatUser['tree'] )))->setInc('subCount', 1); // 所有上级的sub_count加一
					// 向最顶端推送模板消息
					$accessTokenArray = $this->wechatAdvance->getBaseAccess();
					$this->sendAddMsg(array('newId'=>$newId, 'subCount'=>$topWechatUser['subCount']+1), $accessTokenArray['access_token'], $topWechatUser['openId']);
					if( $topId != $mid ) {
						// 向师傅发送模板消息
						$this->sendAddMsg(array('newId'=>$newId, 'subCount'=>$masterWechatUser['subCount']+1), $accessTokenArray['access_token'], $masterWechatUser['openId']);
					}
				}
				
                // 更新师父等级
                /*if ( $this->config['level_config'] and $this->config['level_config'][WechatUserModel::USER_TYPE_FRANCHISED_DEALER] ) { // 已开启金牌会员等级制
                    if ( $mid ) { // 有父级推荐
                        $userDiscount = $this->config['user_discount'];
                        krsort($userDiscount);
                        foreach ( $userDiscount as $k => $v ) {
                            if ( ($masterWechatUser['subCount']+1) >= $v['number'] ) {
                                M("WechatUser")->where(array('cid'=>$this->cid, 'id'=>$mid))->save(array('level', $v['toLevel']*1));
                                break;
                            }
                        }
                    }
                }*/			
				$addWechatUser["isNew"] = 1;
				return $addWechatUser;
			}
		} else {
			if ( $info ) {
				if ( $info['subscribe'] ) { // 已关注时
					$data = array (
							'nickname' => $info['nickname'],
							'face' => $info['headimgurl'],
							'subscribe' => 1,
					);
				} else { // 未关注时
					$data = array (
							'subscribe' => 0,
					);
				}
				$wechatUser = array_merge($wechatUser, $data);
				if( M("WechatUser")->where(array('id' => $wechatUser['id']))->save($data) ) {
					$wechatUser["isFresh"] = 1;
				}
			}
			return $wechatUser;
		}
		return false;
	}
	
	/**
	 * 发送加入消息
	 * @param array $param
	 * array(
	 * 	newId,subCount
	 * )
	 */
	protected function sendAddMsg($param, $accessToken, $openId) {
		$templateId = $this->wechatConfig['templateid']; // "OtEPSHE5NbL6YHT9v4ElTmsbvb6LTq5I2VRLb7lyAcs";
		$templateType = $this->wechatConfig['templateType'] or $templateType = 1;
		if ( $templateType == 1 ) {
			$data = array (
					'first' => array (
							'value' => "恭喜，你有新的朋友加入！",
							'color' => '#0000ee'
					),
					'infotitle' => array (
							'value' => "您有一个新的朋友加入",
							'color' => "#ee0000"
					),
					'infoId' => array (
							'value' => str_pad($param['newId'], 6, '0', STR_PAD_LEFT),
							'color' => '#ee0000'
					),
					'statusType' => array (
							'value' => '会员总数',
							'color' => '#000000',
					),
					'status' => array (
							'value' => '共有会员'.$param['subCount'].'位',
							'color' => '#ee0000'
					),
					'remark' => array (
							'value' => '继续加油，邀请更多的朋友们加入吧~~',
							'color' => '#999999'
					)
			);
		} elseif ( $templateType == 2 ) {
			$data = array (
					'first' => array (
							'value' => "恭喜，你有新的朋友加入！",
							'color' => '#0000ee'
					),
					'schedule' => array (
							'value' => "您有一个新的朋友加入",
							'color' => "#ee0000"
					),
					'time' => array (
							'value' => date('Y-m-d H:i:s', time()),
							'color' => '#ee0000'
					),
					'remark' => array (
							'value' => "共有会员:{$param['subCount']}位\n继续加油，邀请更多的朋友们加入吧~~",
							'color' => '#999999'
					)
			);
		}
		$result = $this->wechatAdvance->sendTemplateMessage($accessToken, $openId, $templateId, $data);
		return $result;
	}
	
	/**
	 * 退出
	 * 
	 * @return \Utuo\DistributionShopForeground
	 */
	protected function setLogout() {
		session($this->sessionKey, null);
		if (session("sessionKeys"))
			$this->sessionKeys = unserialize(session("sessionKeys"));
		else
			$this->sessionKeys = array ();
		foreach ($this->sessionKeys as $name) {
			session($name, null);
		}
		return $this;
	}
	
	/**
	 * AJAX返回正确信息
	 *
	 * @param string $msg
	 * @param array $extra
	 * @return
	 *
	 */
	protected function ajaxSuccess($msg = '操作成功', $extra = null, $redirectUrl = null, $redirectDelay = 1) {
		$data['error'] = 0;
		$data['msg'] = $msg;
		is_null($extra) or $data['extra'] = $extra;
		is_null($redirectUrl) or $data['redirect'] = array (
				'url' => $redirectUrl,
				'delay' => $redirectDelay * 1000 
		);
		header('Content-Type:application/json; charset=utf-8');
		exit(json_encode($data));
	}
	
	/**
	 * AJAX返回错误信息
	 *
	 * @param string $msg
	 * @param array $extra
	 * @return \Utuo\BackgroundController
	 */
	protected function ajaxError($msg = '操作失败', $extra = null, $redirectUrl = null, $redirectDelay = 1) {
		$data['error'] = 1;
		$data['msg'] = $msg;
		is_null($extra) or $data['extra'] = $extra;
		is_null($redirectUrl) or $data['redirect'] = array(
			'url' => $redirectUrl,
			'delay' => $redirectDelay * 1000
		);
		header('Content-Type:application/json; charset=utf-8');
		exit(json_encode($data));
	}
	
	/**
	 * 获取表单选择列表
	 *
	 * @param array $options
	 * @param string $default
	 * @param string $firstOption
	 * @return string
	 */
	protected function getOption($options, $default = null, $firstOption = null) {
		empty($options) && $options = array ();
		$ret = array ();
		empty($firstOption) or $ret[] = "<option value=''>$firstOption</option>";
		foreach ($options as $k => $v) {
			$selected = !is_null($default) && $default == $k ? " selected='selected'" : '';
			$ret[] = "<option value='$k'$selected>$v</option>";
		}
		return implode("\n", $ret);
	}
	
	/**
	 * 读写分离开关
	 * @param unknown $status
	 */
	protected function rwSeparate( $status ) {
		DBRW::openAndClose($status);
	}
	
	/**
	 * 当前地址
	 * @param array $param 增加的参数
	 */
	protected function getCurrentUrl( $attach = array() ) {
		unset($_REQUEST[C('TOKEN_NAME')]);
		function toArray($data, $level, $path, &$result) {
			foreach ($data as $k => $v) {
				$p = $path . ($level ? "[" . $k . "]" : $k);
				if (is_array($v)) {
					toArray($v, 1 + $level, $p, $result);
				} else {
					$result[$p] = $v;
				}
			}
			return $result;
		}
		$soure = array ();
		$attach and $soure = array_merge($soure, $attach);
		$result = toArray($_REQUEST, 0, "", $soure);
		$queryString = "";
		foreach ($result as $k => $v)
			$queryString .= $k . "=" . $v . "&";
		$queryString = trim($queryString, "&");
		return url(null, CONTROLLER_NAME, ACTION_NAME, "") . "?" . $queryString;
	}
	
	/**
	 * 响应消息
	 * @param unknown $msg
	 */
	protected function responseMsg( $msg, $error = 1, $wparam = array() ) {
		$fun = "";
		if ( IS_AJAX ) {
			$fun = $error ? "ajaxError" : "ajaxSuccess";
			$this->$fun ( $msg, $wparam );
		} else {
			$fun = $error ? "error" : "success";
			$this->$fun( $msg );
		}
		exit;
	}
	
	/**
	 * 获得模型配置信息
	 */
	private function getModelConfig() {
		return D("My/DistributionShop")->getShopConfig($this->cid);
	}
	
	/**
	 * 当前URL
	 * 
	 * @param 附加参数
	 */
	private function getRedirectUrl($wparam) {
		$queryString = $_SERVER['QUERY_STRING'];
	    $wparam = empty($wparam) ? $this->redirectParams : array_merge($this->redirectParams, $wparam); // 加入额外跳转参数
		if ($wparam) {
			$params = array ();
			parse_str($queryString, $params);
			$params = array_merge($params, $_GET); // 加入pathinfo url中的参数
			foreach ($wparam as $k => $v) {
				$params[$k] = $v;
			}
			unset($params['state']);
			unset($params['code']);
			$paramsTmp = array ();
			foreach ($params as $k => $v) {
				$paramsTmp[] = $k . "=" . $v;
			}
			$queryString = join('&', $paramsTmp);
		}
		$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . (!empty($queryString) ? '?' . $queryString : '');
		return $url;
	}
	
	/**
	 * 设置微信id
	 * @param $openId 要设置的微信号(不传将从request与session中获取)
	 */
	protected  function setOpenId( $openId = 0 ) {
		$this->openId = $openId ? $openId : 0; // I('request.open_id', 0)
		$sessionOpenid = session($this->openIdKey);
		if ( $this->openId ) {
			session($this->openIdKey, $this->openId);
		} else {
			$this->openId = $sessionOpenid ? $sessionOpenid : 0;
		}
		$this->assign("openId", $this->openId);
	}
	
	/**
	 * 验证代理商
	 */
	private function checkAid( $aid ) {
		return M("Agent")->where('cid=%d and id=%d', $this->cid, $aid)->count() ? true : false;
	}
}
